<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="产品" prop="cate_id">
        <el-select
          v-model="queryParams.cate_id"
          placeholder="请选择产品"
          filterable
          clearable
          style="width:150px"
        >
          <el-option
            v-for="product in productList"
            :key="product.id"
            :label="product.name"
            :value="product.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="渠道" prop="channel_id">
        <el-select
          v-model="queryParams.channel_id"
          placeholder="请选择渠道"
          filterable
          clearable
           style="width:150px"
        >
          <el-option
            v-for="channel in channelList"
            :key="channel.id"
            :label="channel.channel_name"
            :value="channel.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型" prop="recharge_type">
        <el-select
          v-model="queryParams.recharge_type"
          placeholder="业务类型"
          clearable
          style="width: 240px"
        >
          <el-option label="话费" :value="1" />
          <el-option label="流量" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="运营商" prop="isp">
        <el-select
          v-model="queryParams.isp"
          placeholder="运营商"
          clearable
          style="width: 240px"
        >
          <el-option label="移动" :value="1" />
          <el-option label="联通" :value="2" />
          <el-option label="电信" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
          style="width: 240px"
        >
          <!-- v-for="dict in dict.type.sys_normal_disable" -->
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          small="small"
          style="width: 240px"
          value-format="x"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          size="small"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" size="small" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- v-hasPermi="['api:v1:addChannelProduct']" -->
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['api:czChannelProduct:addProduct']"
          >新增渠道产品</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <!-- v-hasPermi="['api:v1:setChannelPrice']" -->
        <el-button
          type="success"
          plain
          icon="Edit"
          size="small"
          :disabled="multiple"
          @click="handlePrice"
          v-hasPermi="['api:czChannelProduct:setPrice']"
          >批量修改进价</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <!-- v-hasPermi="['api:v1:delChannelProduct']" -->
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['api:czChannelProduct:destroyProduct']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      border
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <!-- <el-table-column label="产品名称" align="center" prop="spec.name" /> -->
      <el-table-column label="产品分类" align="center" prop="spec.cate.name" />

      <el-table-column label="原价" align="center" prop="spec.market_price" />
      <el-table-column label="面值" align="center" prop="spec.face_value" />
      <!-- <el-table-column label="原价" align="center" prop="spec.market_price" /> -->
      <el-table-column label="进价" align="center" prop="channel_price" />
      <el-table-column prop="type" label="业务类型" align="center">
        <template #default="scope">
          <template v-if="scope.row.spec">
            <el-tag type="success" v-if="scope.row.spec.recharge_type == 1">
              话费</el-tag
            >
            <el-tag v-if="scope.row.spec.recharge_type == 2"> 流量</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="isp" label="运营商" align="center">
        <template #default="scope">
          <template v-if="scope.row.spec">
            <el-tag type="success" v-if="scope.row.spec.isp == 1"> 移动</el-tag>
            <el-tag type="info" v-if="scope.row.spec.isp == 2"> 联通</el-tag>
            <el-tag v-if="scope.row.spec.isp == 3"> 电信</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.status == 1"> 启用</el-tag>
          <el-tag type="warning" v-else>禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="渠道"
        align="center"
        prop="channel.channel_name"
      />
      <el-table-column label="产品备注" align="center" prop="spec.remark" />
      <el-table-column
        label="对接编码"
        align="center"
        prop="channel_api_code"
      />
      <el-table-column
        label="是否延迟"
        align="center"
        prop="channel_api_code"
      >

      <template #default="scope">
          <el-tag type="success" v-if="scope.row.is_defer == 1"> 是</el-tag>
          <el-tag type="warning" v-else>否</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="created_at"
        width="180"
      >
        <template #default="scope">
          <span>{{ scope.row.created_time }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="修改时间"
        align="center"
        prop="updated_time"
        width="180"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- v-hasPermi="['api:v1:addChannelProduct']" -->
          <el-button
            size="small"
            type="primary"
            link
            icon="Edit"
            v-hasPermi="['api:czChannelProduct:updateProduct']"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <!-- v-hasPermi="['api:v1:delChannelProduct']" -->
          <el-button
            size="small"
            type="primary"
            link
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['api:czChannelProduct:destroyProduct']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      title="修改渠道产品"
      v-model="open"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="产品名称">
          <el-input v-model="spec.name" small="small" :disabled="true" />
        </el-form-item> -->
        <el-form-item label="产品分类">
          <el-input v-model="product.name" small="small" :disabled="true" />
        </el-form-item>
        <el-form-item label="面值">
          <el-input v-model="spec.face_value" small="small" :disabled="true" />
        </el-form-item>
        <el-form-item label="渠道">
          <el-input
            v-model="channel.channel_name"
            small="small"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="进价" prop="channel_price">
          <el-input
            v-model="form.channel_price"
            placeholder="请输入进价"
            clearable
            small="small"
          />
          <span>注意这里是价格，不是折扣！！！！</span>
        </el-form-item>
        <el-form-item label="对接编码" prop="channel_api_code">
          <el-input
            v-model="form.channel_api_code"
            placeholder="请输入对接编码"
            clearable
            small="small"
          />
        </el-form-item>
        <el-form-item label="是否延迟" prop="is_defer">
          <el-select
              v-model="form.is_defer"
              placeholder="是否延迟"
              clearable
              style="width: 240px"
            >
              <!-- <el-option
                v-for="dict in dict.type.cz_product_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              /> -->
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      title="批量设置进价"
      v-model="priceOpen"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <!-- {{ multiplePriceList[0] }} -->
      <el-table :data="multiplePriceList">
        <!-- <el-table-column label="产品名称" align="center" prop="spec" /> -->
        <el-table-column
          label="产品分类"
          align="center"
          prop="spec.cate.name"
        />
        <el-table-column label="面值" align="center" prop="spec.face_value" />
        <el-table-column label="原价" align="center" prop="spec.market_price" />
        <el-table-column
          label="渠道"
          align="center"
          prop="channel.channel_name"
        />
        <el-table-column label="进价" align="center" prop="channel_price" />
      </el-table>
      <br />
      <el-form
        ref="priceForm"
        :model="priceForm"
        :rules="priceRules"
        label-width="100px"
      >
        <el-form-item label="折扣(原价)" prop="discount">
          <el-input-number
            v-model="priceForm.discount"
            :precision="2"
            :step="1"
            :min="0"
            :max="100"
            placeholder="请输入折扣"
          ></el-input-number>
        </el-form-item>
        <p>进价 = 原价 * 折扣 / 100，例如：100*92.5/100=92.5</p>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPriceForm">确 定</el-button>
          <el-button @click="cancelPrice">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  listChannelProduct,
  setMutiplePrice,
  getChannelProduct,
  updateChannelProduct,
  delChannelProduct,
} from "@/api/channel/channelProduct";
// import { getListAll as listAllCzProduct } from "@/api/platform/czProductSpec";
import { getAllList as listAllCzCate } from "@/api/platform/czProductCate";

import { getAllList as listAllChannel } from "@/api/channel";

import { isNumberStr } from "@/utils/index";

export default {
  name: "rechargechannelproduct",
  //   "cz_product_type", "cz_isp"
  //   dicts: ["sys_normal_disable", "sys_yes_no"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      multipleSelection: [],
      multiplePriceList: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      dataList: [],
      productList: [],
      channelList: [],
      currentChannelSetting: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      priceOpen: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        channel_name: undefined,
        channel_code: undefined,
        callback_type: undefined,
        is_sync: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      product: {},
      spec: {},
      channel: {},
      priceForm: {},
      // 表单校验
      rules: {
        channel_price: [
          { required: true, message: "请输入进价", trigger: "blur" },
        ],
        channel_api_code: [
          { required: true, message: "请输入对接编码", trigger: "blur" },
        ],
      },
      priceRules: {
        discount: [{ required: true, message: "请输入折扣", trigger: "blur" }],
      },
    };
  },

  watch: {
    "priceForm.discount": function () {
      if (this.priceForm.discount) {
        this.multiplePriceList.forEach((ele, index) => {
          ele.channel_price =
            (ele.spec.market_price * this.priceForm.discount) / 100;
        });
      }
    },
  },
  created() {
    this.getProductList();
    this.getChannelList();
    this.getList();
  },
  methods: {
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      const obj = this.addDateRange(this.queryParams, this.dateRange);
      obj.created_time = [obj.params.beginTime, obj.params.endTime];
      delete obj.params;
      listChannelProduct(obj).then((response) => {
        this.dataList = response.data.items;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    getProductList() {
      listAllCzCate().then((response) => {
        this.productList = response.data;
        console.log(this.productList);
      });
    },
    getChannelList() {
      listAllChannel().then((response) => {
        this.channelList = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.currentChannelSetting = [];
      this.form = {
        id: undefined,
        channel_name: undefined,
        channel_code: undefined,
        setting: undefined,
        callback_type: undefined,
        callback_url: undefined,
        is_sync: "N",
        status: "1",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ path: "addChannelProduct" });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multipleSelection = selection;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getChannelProduct(id).then((response) => {
        this.form = response.data;
        this.product = this.form.product;
        console.log(this.product)
        this.spec = this.form.spec;
        this.channel = this.form.channel;
        this.open = true;
        this.title = "修改渠道产品";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateChannelProduct(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictIds = row.id ? [row.id] : this.ids;
      //   console.log(dictIds);
      this.$modal
        .confirm('是否确认删除编号为"' + dictIds + '"的数据项？')
        .then(function () {
          return delChannelProduct(dictIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleChannelChange(code) {
      if (code) {
        this.currentChannelSetting = this.channelList[code]
          ? this.channelList[code].setting
          : [];
        this.form.callback_type = this.channelList[code]
          ? this.channelList[code].callback_type
          : 1;
      }
    },
    handlePrice() {
      this.priceForm = {};
      this.multiplePriceList = JSON.parse(
        JSON.stringify(this.multipleSelection)
      );
      this.priceOpen = true;
    },
    cancelPrice() {
      this.priceOpen = false;
      this.priceForm = {};
    },
    submitPriceForm() {
      this.$refs["priceForm"].validate((valid) => {
        if (valid) {
          if (!isNumberStr(this.priceForm.discount)) {
            this.$modal.msgError("折扣必须是0-100之间的数字。");
            return false;
          }
          const items = this.multiplePriceList.map((item) => {
            return {
              channel_id: item.channel_id,
              product_id: item.product_id,
              spec_id: item.spec_id,
              channel_price:
                (item.spec.market_price * this.priceForm.discount) / 100,
            };
          });
          setMutiplePrice({ ...this.priceForm, items }).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.priceOpen = false;
            this.getList();
          });
        }
      });
    },
    changeInput(val) {
      if (isNumberStr(val)) {
        this.multiplePriceList.forEach((ele, index) => {
          ele.channel_price =
            (ele.spec.market_price * this.priceForm.discount) / 100;
        });
      }
    },
  },
};
</script>
